package com.atmilan.quartz.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.MybatisPlusConfig;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.mapper.StoreProductMapper;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.BuyerProductSku;
import com.atmilan.quartz.model.entity.buyer.MoneyExchange;
import com.atmilan.quartz.model.entity.crmeb.ChannelMerchant;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrResult;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.model.entity.crmeb.StoreProductCate;
import com.atmilan.quartz.model.entity.crmeb.StoreProductCoupon;
import com.atmilan.quartz.model.entity.crmeb.StoreProductDescription;
import com.atmilan.quartz.model.entity.crmeb.StoreProductMer;
import com.atmilan.quartz.model.entity.crmeb.StoreProductNorm;
import com.atmilan.quartz.model.entity.crmeb.StoreProductTranslate;
import com.atmilan.quartz.model.entity.europe.EuropeProductSku;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.IChannelMerchantService;
import com.atmilan.quartz.service.IMoneyExchangeService;
import com.atmilan.quartz.service.IStoreProductAttrLuxuryService;
import com.atmilan.quartz.service.IStoreProductAttrResultLuxuryService;
import com.atmilan.quartz.service.IStoreProductAttrResultService;
import com.atmilan.quartz.service.IStoreProductAttrService;
import com.atmilan.quartz.service.IStoreProductAttrValueLuxuryService;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductCateLuxuryService;
import com.atmilan.quartz.service.IStoreProductCateService;
import com.atmilan.quartz.service.IStoreProductCouponLuxuryService;
import com.atmilan.quartz.service.IStoreProductCouponService;
import com.atmilan.quartz.service.IStoreProductDescriptionService;
import com.atmilan.quartz.service.IStoreProductLuxuryService;
import com.atmilan.quartz.service.IStoreProductMerService;
import com.atmilan.quartz.service.IStoreProductNormService;
import com.atmilan.quartz.service.IStoreProductService;
import com.atmilan.quartz.service.IStoreProductTranslateService;
import com.atmilan.quartz.service.ISystemAttachmentService;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerProductSkuService;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeProductSkuService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.utils.ImageSearchUtils;
import com.atmilan.quartz.utils.PriceUtil;
import com.atmilan.quartz.utils.TableNameUtil;
import com.atmilan.quartz.utils.unibuy.client.OpenHttp;
import com.atmilan.quartz.utils.unibuy.util.MD5Util;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

@Slf4j
@Service
@DS("crmeb")
public class StoreProductServiceImpl extends ServiceImpl<StoreProductMapper, StoreProduct> implements IStoreProductService {
    @Resource
    private StoreProductMapper storeProductMapper;
    @Autowired
    private ISystemAttachmentService systemAttachmentService;
    @Autowired
    private IStoreProductAttrService storeProductAttrService;
    @Autowired
    IStoreProductNormService storeProductNormService;
    @Autowired
    private IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private IStoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private IStoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private IStoreProductCouponService storeProductCouponService;
    @Autowired
    private IStoreProductCateService storeProductCateService;
    /**** luxury相关处理 *****/
    @Autowired
    private IStoreProductLuxuryService storeProductLuxuryService;
    @Autowired
    private IStoreProductAttrLuxuryService storeProductAttrLuxuryService;
    @Autowired
    private IStoreProductAttrValueLuxuryService storeProductAttrValueLuxuryService;
    @Autowired
    private IStoreProductAttrResultLuxuryService storeProductAttrResultLuxuryService;
    @Autowired
    private IStoreProductCouponLuxuryService storeProductCouponLuxuryService;
    @Autowired
    private IStoreProductCateLuxuryService storeProductCateLuxuryService;
    @Autowired
    private IBuyerProductSkuService buyerProductSkuService;
    @Autowired
    private IEuropeProductSkuService europeProductSkuService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private IStoreProductMerService storeProductMerService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private IStoreProductTranslateService storeProductTranslateService;
    @Autowired
    private IMoneyExchangeService moneyExchangeService;
    private static List<Integer> brandIds = Arrays.asList(251,3039,16992,252,2219,4150,4250,4251,17573,5132,4250);

    /** 百度翻译 **/
    private static final String BDURL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private static final String APPID = "20230202001547479";
    private static final String SECRET = "ooWURbYzHCb8hfIijkLE";
    private static final String SALT = "435660288"; // 随机数
    private static List<Integer> translateIds = Arrays.asList(ProductTypeEnum.GB.getCode(), ProductTypeEnum.BELLETTINI.getCode(), 
			ProductTypeEnum.LEAM.getCode(), ProductTypeEnum.VIETTI.getCode(), ProductTypeEnum.COLTORTI.getCode()
		    );
    
    /**
     * 下发到crmeb
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @return
     * @return StoreProduct
     * @throws
     */
    private StoreProduct priceAdjustCrmeb(StoreProduct product) {
        // 欧洲商品
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
        	PriceResult priceResult = priceUtil.eur2Rmb(product.getSourceCost());
            product.setCost(PriceUtil.calePrice(priceResult.getPrice(), Constants.RATE_EUROPE_2_CRMEB_COST));
            product.setPrice(PriceUtil.calePrice(priceResult.getPrice().multiply(new BigDecimal(Constants.RATE_EUROPE_2_CRMEB)), Constants.RATE_EUROPE_2_CRMEB_FLOAT));
            product.setExchangeRate(priceResult.getExchangeRate());
        } else {
            product.setCost(PriceUtil.calePrice(product.getSourceCost(), Constants.RATE_BUYER_2_CRMEB_COST));
            product.setPrice(PriceUtil.calePrice(product.getSourceCost().multiply(new BigDecimal(Constants.RATE_BUYER_2_CRMEB)), Constants.RATE_BUYER_2_CRMEB_FLOAT));
        }
        // 费率
//        BigDecimal promotePrice = product.getPromotePrice();
//        product.setPromotePrice(PriceUtil.calePrice(promotePrice, Constants.RATE_CRMEB_2_CRMEB));

        return product;
    }
    
    // 下发到luxury
    private StoreProduct priceAdjustLuxury(StoreProduct product) {
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
        	PriceResult priceResult = priceUtil.eur2Rmb(product.getSourceCost());
            product.setCost(PriceUtil.calePrice(priceResult.getPrice(), Constants.RATE_EUROPE_2_LUXURY_COST));
            product.setPrice(PriceUtil.calePrice(priceResult.getPrice().multiply(new BigDecimal(Constants.RATE_EUROPE_2_LUXURY)), Constants.RATE_EUROPE_2_LUXURY_FLOAT));
            product.setExchangeRate(priceResult.getExchangeRate());
        } else {
            product.setCost(PriceUtil.calePrice(product.getSourceCost(), Constants.RATE_BUYER_2_LUXURY_COST));
            product.setPrice(PriceUtil.calePrice(product.getSourceCost().multiply(new BigDecimal(Constants.RATE_BUYER_2_LUXURY)), Constants.RATE_BUYER_2_LUXURY_FLOAT));
        }
        
//        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
//            product.setPrice(PriceUtil.calePrice(product.getPrice(), Constants.RATE_EUROPE_2_LUXURY));
//            return product;
//        }
//        // 费率
//        product.setPrice(PriceUtil.calePrice(product.getPrice(), Constants.RATE_BUYER_2_LUXURY));
        
        return product;
    }
    /*private void valuePriceAdjustCrmeb(StoreProductAttrValue value, StoreProduct product) {
        // 欧洲商品只计算价格
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
            value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_LUXURY_2_CRMEB));
            return;
        }
        value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_CRMEB_2_CRMEB));
    }
    private void valuePriceAdjustLuxury(StoreProductAttrValue value, StoreProduct product) {
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
            value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_LUXURY_2_LUXURY));
        } else {
            value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_LUXURY_2_CRMEB));
        }
    }*/

    /**
     * 新增产品
     * @param storeProductCrmebRequest 新增产品request对象
     * @return 新增结果
     */
    @Override
    public boolean save(StoreProductCrmebRequest storeProductCrmebRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProduct);
        storeProduct.setCreateTime(new Date());
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));
        
        //计算价格
        calcPriceForAttrValues(storeProductCrmebRequest, storeProduct);
        // 不要显示成本价，显示最低sku售价
        double costPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getCost().intValue()).min().getAsDouble();
        //原成本价
        BigDecimal sourceCost = storeProductCrmebRequest.getSourceCost();
        double sellPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getPrice().intValue()).min().getAsDouble();
        // 原价
        double otPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getOtPrice().intValue()).min().getAsDouble();
        int stock = storeProductCrmebRequest.getAttrValue().stream().mapToInt(e -> e.getStock()).sum();
        // 过滤库存为0的数据
        if(0 >= stock) {
            log.info("--------------- 丢弃库存为0商品, 商品id: {} ---------------", storeProductCrmebRequest.getId());
            return false;
        }
        
        storeProduct.setCost(BigDecimal.valueOf(costPrice));
        storeProduct.setSourceCost(sourceCost);
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);

        // 分别计算luxury商品和buy价格
        StoreProduct storeProductLuxury = new StoreProduct();
        BeanUtils.copyProperties(storeProduct, storeProductLuxury);
        storeProduct = priceAdjustCrmeb(storeProduct);
        storeProductLuxury = priceAdjustLuxury(storeProductLuxury);
        storeProductLuxury.setPostage(storeProduct.getPostage());

        //保存数据
        boolean save = this.save(storeProduct);
        storeProductLuxuryService.save(storeProductLuxury);
        if (null != storeProduct.getId()) {
            storeProductCrmebRequest.setId(storeProduct.getId());
        }
        if (storeProductCrmebRequest.getSpecType()) { // 多属性
            List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
            List<StoreProductAttr> attrsLuxury = attrs.stream().map(t -> {
                StoreProductAttr obj = new StoreProductAttr();
                BeanUtils.copyProperties(t, obj);
                return obj;
            }).collect(Collectors.toList());
            
            Integer id = storeProduct.getId();
            attrs.forEach(e -> {
                e.setProductId(id);
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            Integer idLuxury = storeProductLuxury.getId();
            attrsLuxury.forEach(e -> {
                e.setProductId(idLuxury);
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            boolean attrAddResult = storeProductAttrService.saveBatch(attrs);
            storeProductAttrLuxuryService.saveOrUpdateBatch(attrsLuxury);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
        } else { // 单属性
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            StoreProductAttr singleAttrLuxury = new StoreProductAttr();
            singleAttrLuxury.setProductId(storeProductLuxury.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            storeProductAttrLuxuryService.save(singleAttrLuxury);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            BigDecimal commissionL1 = BigDecimal.ZERO;
            BigDecimal commissionL2 = BigDecimal.ZERO;
            if (storeProductCrmebRequest.getAttrValue().size() > 0) {
                commissionL1 = null != storeProductCrmebRequest.getAttrValue().get(0).getBrokerage() ? storeProductCrmebRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                commissionL2 = null != storeProductCrmebRequest.getAttrValue().get(0).getBrokerageTwo() ? storeProductCrmebRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
            }

            singleAttrValue.setProductId(storeProduct.getId());
            singleAttrValue.setStock(storeProduct.getStock());
            singleAttrValue.setSuk("默认");
            singleAttrValue.setSales(storeProduct.getSales());
            singleAttrValue.setPrice(storeProduct.getPrice());
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
            singleAttrValue.setCost(storeProduct.getCost()).setBarCode(storeProduct.getBarCode());
            singleAttrValue.setOtPrice(storeProduct.getOtPrice());
            singleAttrValue.setBrokerage(commissionL1);
            singleAttrValue.setBrokerageTwo(commissionL2);
            StoreProductAttrValue singleAttrValueLuxury = new StoreProductAttrValue();
            BeanUtils.copyProperties(singleAttrValue, singleAttrValueLuxury);
            singleAttrValueLuxury.setProductId(storeProductLuxury.getId());
            // 计算价格
            singleAttrValue.setPrice(storeProduct.getPrice());
            singleAttrValueLuxury.setPrice(storeProductLuxury.getPrice());
            if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                singleAttrValue.setCost(storeProduct.getCost());
            }

            // 查询sku信息
            if(ProductTypeEnum.EUROPE.getCode() == storeProduct.getIsEurope()) {
                EuropeProductSku europeProductSku = europeProductSkuService.getOne(Wrappers.<EuropeProductSku>lambdaQuery()
                        .eq(EuropeProductSku :: getGoodsId, storeProduct.getBarCode().substring(4, storeProduct.getBarCode().length()))
                        .eq(EuropeProductSku :: getSuk, singleAttrValue.getSuk())
                        .last("LIMIT 1")
                        );
                singleAttrValue.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                singleAttrValueLuxury.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
            } else if(ProductTypeEnum.BUYER.getCode() == storeProduct.getIsEurope()) {
                BuyerProductSku buyerProductSku = buyerProductSkuService.getOne(Wrappers.<BuyerProductSku>lambdaQuery()
                        .eq(BuyerProductSku :: getGoodsId, storeProduct.getBarCode().substring(4, storeProduct.getBarCode().length()))
                        .eq(BuyerProductSku :: getSuk, singleAttrValue.getSuk())
                        .last("LIMIT 1")
                        );
                singleAttrValue.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                singleAttrValueLuxury.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
            }
        
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            storeProductAttrValueLuxuryService.save(singleAttrValueLuxury);
            if (!saveOrUpdateResult) {
                log.warn("新增属性详情失败");
            }
        }
        if (null != storeProductCrmebRequest.getAttrValue() && storeProductCrmebRequest.getAttrValue().size() > 0) {
            // 批量设置attrValues对象的商品id
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequestLuxury = new ArrayList<StoreProductAttrValueRequest>();

            List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
            List<StoreProductAttrValue> storeProductAttrValuesLuxury = new ArrayList<>();
            for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                attrValuesRequest.setProductId(storeProduct.getId());
                StoreProductAttrValue spav = new StoreProductAttrValue();
                StoreProductAttrValue spavLuxury = new StoreProductAttrValue();
                BeanUtils.copyProperties(attrValuesRequest, spav);
                BeanUtils.copyProperties(attrValuesRequest, spavLuxury);
                spavLuxury.setProductId(storeProductLuxury.getId());
                //设置sku字段
                if (null == attrValuesRequest.getAttrValue()) {
                    break;
                }
                List<String> skuList = new ArrayList<>();
                for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                    skuList.add(vo.getValue());
                    spav.setSuk(String.join(",", skuList));
                    spavLuxury.setSuk(String.join(",", skuList));
                }

                // 查询sku信息
                if(ProductTypeEnum.EUROPE.getCode() == storeProduct.getIsEurope()) {
                    EuropeProductSku europeProductSku = europeProductSkuService.getOne(Wrappers.<EuropeProductSku>lambdaQuery()
                            .eq(EuropeProductSku :: getGoodsId, storeProduct.getBarCode().substring(4, storeProduct.getBarCode().length()))
                            .eq(EuropeProductSku :: getSuk, spav.getSuk())
                            .last("LIMIT 1")
                            );
                    spav.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                    spavLuxury.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                } else if(ProductTypeEnum.BUYER.getCode() == storeProduct.getIsEurope()) {
                    BuyerProductSku buyerProductSku = buyerProductSkuService.getOne(Wrappers.<BuyerProductSku>lambdaQuery()
                            .eq(BuyerProductSku :: getGoodsId, storeProduct.getBarCode().substring(4, storeProduct.getBarCode().length()))
                            .eq(BuyerProductSku :: getSuk, spav.getSuk())
                            .last("LIMIT 1")
                            );
                    spav.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                    spavLuxury.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                }
                
                spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                spavLuxury.setImage(spav.getImage());
                spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                spavLuxury.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));

                // 意大利商品result
                StoreProductAttrValueRequest attrValuesRequestLuxury = new StoreProductAttrValueRequest();
                BeanUtils.copyProperties(attrValuesRequest, attrValuesRequestLuxury);
                // 计算价格
                spav.setPrice(storeProduct.getPrice());
                spavLuxury.setPrice(storeProductLuxury.getPrice());
                attrValuesRequest.setPrice(storeProduct.getPrice());
                attrValuesRequestLuxury.setPrice(storeProductLuxury.getPrice());
                attrValuesRequestLuxury.setCost(storeProductLuxury.getCost());
                spav.setCost(storeProduct.getCost());
                attrValuesRequest.setCost(storeProduct.getCost());
                storeProductAttrValuesRequestLuxury.add(attrValuesRequestLuxury);

                storeProductAttrValues.add(spav);
                storeProductAttrValuesLuxury.add(spavLuxury);
            }
            // 保存属性
            if (storeProductAttrValues.size() > 0) {
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                storeProductAttrValueLuxuryService.saveOrUpdateBatch(storeProductAttrValuesLuxury);
                
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0, */storeProduct.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                StoreProductAttrResult attrResultLuxury = new StoreProductAttrResult(/*0,*/ storeProductLuxury.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductAttrValuesRequestLuxury)), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                storeProductAttrResultLuxuryService.save(attrResultLuxury);
                if (!saveOrUpdateResult) {
                    log.warn("新增属性详情失败");
                }
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        // 处理优惠券关联信息
        shipProductCoupons(storeProductCrmebRequest, storeProduct, storeProductLuxury);
        return save;
    }
    
    /**
     * 更新产品
     * @param storeProductCrmebRequest 更新产品request对象
     * @return 更新结果
     */
    @Override
    public boolean update(StoreProductCrmebRequest storeProductCrmebRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProduct);
        storeProduct.setCreateTime(new Date());

        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));

        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));

        calcPriceForAttrValues(storeProductCrmebRequest, storeProduct);

        // 分别计算luxury商品和buy价格
        StoreProduct storeProductLuxury = new StoreProduct();
        BeanUtils.copyProperties(storeProduct, storeProductLuxury);
        storeProduct = priceAdjustCrmeb(storeProduct);
        storeProductLuxury = priceAdjustLuxury(storeProductLuxury);

        boolean saveCount = this.updateById(storeProduct);
        storeProductLuxuryService.updateById(storeProductLuxury);

        // 对attr表做全量更新，删除原有数据保存现有数据
        storeProductAttrService.removeByProductId(storeProduct.getId());
        storeProductAttrLuxuryService.removeByProductId(storeProduct.getId());
        List<StoreProductAttrValue> attrValuelist = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));
        Map<String, StoreProductAttrValue> attrValueMap = attrValuelist == null ? MapUtil.newHashMap() : attrValuelist.stream().collect(Collectors.toMap(StoreProductAttrValue::getSuk, Function.identity()));
        if (CollectionUtils.isNotEmpty(storeProductCrmebRequest.getAttrValue())) {
            for (StoreProductAttrValueRequest attrValueRequest : storeProductCrmebRequest.getAttrValue()) {
                if (null != attrValueRequest.getAttrValue()) {
                    List<String> skuList = new ArrayList<>();
                    for (Map.Entry<String, String> vo : attrValueRequest.getAttrValue().entrySet()) {
                        skuList.add(vo.getValue());
                    }
                    attrValueRequest.setSuk(String.join(",", skuList));
//                    attrValueRequest.setId(attrValueMap.containsKey(attrValueRequest.getSuk()) ? attrValueMap.get(attrValueRequest.getSuk()).getId() : null);
                }

            }
        }

        if (storeProductCrmebRequest.getSpecType()) { //  确认单属性商品的attr参数
            storeProductCrmebRequest.getAttr().forEach(e -> {
                e.setProductId(storeProductCrmebRequest.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
            storeProductAttrService.saveBatch(attrs);
            storeProductAttrLuxuryService.saveOrUpdateBatch(attrs);
            if (CollectionUtils.isNotEmpty(storeProductCrmebRequest.getAttrValue())) {

                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
                List<StoreProductAttrValueRequest> storeProductAttrValuesRequestLuxury = new ArrayList<StoreProductAttrValueRequest>();

                // 批量设置attrValues对象的商品id
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
                List<StoreProductAttrValue> storeProductAttrValuesLuxury = new ArrayList<>();

                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    attrValuesRequest.setProductId(storeProductCrmebRequest.getId());
                    
                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    StoreProductAttrValue spavLuxury = new StoreProductAttrValue();
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    BeanUtils.copyProperties(attrValuesRequest, spavLuxury);
                    spavLuxury.setProductId(storeProductLuxury.getId());
                    
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    spavLuxury.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));

                    // 意大利商品result
                    StoreProductAttrValueRequest attrValuesRequestLuxury = new StoreProductAttrValueRequest();
                    BeanUtils.copyProperties(attrValuesRequest, attrValuesRequestLuxury);
                    // 计算价格
                    spav.setPrice(storeProduct.getPrice());
                    spavLuxury.setPrice(storeProductLuxury.getPrice());
                    attrValuesRequest.setPrice(storeProduct.getPrice());
                    attrValuesRequestLuxury.setPrice(storeProductLuxury.getPrice());
                    attrValuesRequestLuxury.setCost(storeProductLuxury.getCost());
                    storeProductAttrValuesRequestLuxury.add(attrValuesRequestLuxury);
                    if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                        spav.setCost(storeProduct.getCost());
                        attrValuesRequest.setCost(storeProduct.getCost());
                    }

                    // 查询sku信息
                    if(ProductTypeEnum.EUROPE.getCode() == storeProduct.getIsEurope()) {
                        EuropeProductSku europeProductSku = europeProductSkuService.getOne(Wrappers.<EuropeProductSku>lambdaQuery()
                                .eq(EuropeProductSku :: getGoodsId, storeProduct.getBarCode().substring(4, storeProduct.getBarCode().length()))
                                .eq(EuropeProductSku :: getSuk, spav.getSuk())
                                .last("LIMIT 1")
                                );
                        spav.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                        spavLuxury.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                    } else if(ProductTypeEnum.BUYER.getCode() == storeProduct.getIsEurope()) {
                        BuyerProductSku buyerProductSku = buyerProductSkuService.getOne(Wrappers.<BuyerProductSku>lambdaQuery()
                                .eq(BuyerProductSku :: getGoodsId, storeProduct.getBarCode().substring(4, storeProduct.getBarCode().length()))
                                .eq(BuyerProductSku :: getSuk, spav.getSuk())
                                .last("LIMIT 1")
                                );
                        spav.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                        spavLuxury.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                    }

                    storeProductAttrValues.add(spav);
                    storeProductAttrValuesLuxury.add(spavLuxury);
                }
                storeProductAttrValueService.removeByProductId(storeProduct.getId());

                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                storeProductAttrValueLuxuryService.saveOrUpdateBatch(storeProductAttrValuesLuxury);
                // attrResult整存整取，不做更新
                storeProductAttrResultService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, storeProduct.getId()));
                storeProductAttrResultLuxuryService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, storeProduct.getId()));

                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0,*/ storeProduct.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                StoreProductAttrResult attrResultLuxury = new StoreProductAttrResult(/*0, */storeProduct.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductAttrValuesRequestLuxury)), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                storeProductAttrResultLuxuryService.save(attrResultLuxury);
                if (!saveOrUpdateResult) {
                    log.warn("编辑属性详情失败");
                }

            }
        } else {
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            storeProductAttrLuxuryService.save(singleAttr);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            if (storeProductCrmebRequest.getAttrValue().size() == 0) {
                log.warn("attrValue不能为空");
            }
            StoreProductAttrValueRequest attrValueRequest = storeProductCrmebRequest.getAttrValue().get(0);
            BeanUtils.copyProperties(attrValueRequest, singleAttrValue);
            singleAttrValue.setProductId(storeProduct.getId());
            singleAttrValue.setSuk("默认");
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(singleAttrValue.getImage()));
            
            StoreProductAttrValue singleAttrValueLuxury = new StoreProductAttrValue();
            BeanUtils.copyProperties(singleAttrValue, singleAttrValueLuxury);
            singleAttrValueLuxury.setProductId(storeProductLuxury.getId());

            // 计算价格
            singleAttrValue.setPrice(storeProduct.getPrice());
            singleAttrValueLuxury.setPrice(storeProductLuxury.getPrice());
            if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                singleAttrValue.setCost(storeProduct.getCost());
            }
            storeProductAttrValueService.removeByProductId(storeProduct.getId());
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            storeProductAttrValueLuxuryService.saveOrUpdate(singleAttrValueLuxury);
            if (!saveOrUpdateResult) {
                log.warn("新增属性详情失败");
            }
        }

        // 处理分类辅助表
        if (null != storeProductCrmebRequest.getCateIds()) {
            for (int i = 0; i < storeProductCrmebRequest.getCateIds().size(); i++) {
                Integer cateid = storeProductCrmebRequest.getCateIds().get(i);
                StoreProductCate storeProductCate = new StoreProductCate(storeProduct.getId(), cateid, Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
                LambdaUpdateWrapper<StoreProductCate> luw = new LambdaUpdateWrapper<>();
                luw.set(StoreProductCate::getProductId, storeProductCate.getProductId());
                luw.set(StoreProductCate::getCateId, storeProductCate.getCateId());
                luw.set(StoreProductCate::getAddTime, storeProductCate.getAddTime());
                storeProductCateService.update(luw);
                storeProductCateLuxuryService.update(luw);
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        //productSearchService.updateProductData(storeProduct.getId());
        // 处理优惠券关联信息
        shipProductCoupons(storeProductCrmebRequest, storeProduct, storeProductLuxury);
        return saveCount;
    }

    @Override
    public StoreProduct getByBarCode(String barCode, Integer suppliersId, String keyword) {
//        return getOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getBarCode, barCode)
//                .or(suppliersId != null, qr -> qr.eq(StoreProduct::getSuppliersId, suppliersId)
//                        .eq(StoreProduct::getKeyword, keyword))
//                .last("LIMIT 1"));
        return getOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getBarCode, barCode)
                .last("LIMIT 1"));
    }

    /**
     * 计算产品属性之中最大和最小的价格，新增和编辑使用
     * @param storeProductCrmebRequest 分析的参数
     * @param storeProduct 当前操作的产品
     */
    private void calcPriceForAttrValues(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct) {
        // 不要显示成本价，显示最低sku售价
        double costPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getCost().doubleValue()).min().getAsDouble();

        //原成本价
        BigDecimal sourceCost = storeProductCrmebRequest.getSourceCost();

        double sellPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getPrice().doubleValue()).min().getAsDouble();
        // 原价
        double otPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getOtPrice().doubleValue()).min().getAsDouble();

        int stock = storeProductCrmebRequest.getAttrValue().stream().mapToInt(e -> e.getStock()).sum();
        storeProduct.setCost(BigDecimal.valueOf(costPrice));
        storeProduct.setSourceCost(sourceCost);
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);
    }

    /**
     * 设置优惠券信息
     * @param storeProductCrmebRequest 商品request信息
     * @param storeProduct 商品信息
     */
    private void shipProductCoupons(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct,  StoreProduct storeProductLuxury) {
        if (null != storeProductCrmebRequest.getCouponIds() && storeProductCrmebRequest.getCouponIds().size() > 0) {
            storeProductCouponService.deleteByProductId(storeProduct.getId());
            storeProductCouponLuxuryService.deleteByProductId(storeProductLuxury.getId());
            List<StoreProductCoupon> spcs = new ArrayList<>();
            List<StoreProductCoupon> spcsLuxury = new ArrayList<>();
            for (Integer couponId : storeProductCrmebRequest.getCouponIds()) {
                StoreProductCoupon spc = new StoreProductCoupon(storeProduct.getId(), couponId, Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
                StoreProductCoupon spcLuxury = new StoreProductCoupon(storeProductLuxury.getId(), couponId, Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
                spcs.add(spc);
                spcsLuxury.add(spcLuxury);
            }
            storeProductCouponService.saveCoupons(spcs);
            storeProductCouponLuxuryService.saveCoupons(spcsLuxury);
        }
    }

    @Override
    public void deleteAll() {
        storeProductMapper.deleteAll();
    }
    
    /**
     * 文本翻译
     * @author daigb
     * @throws IOException 
     * @date:  2023-01-30 10:14
     */
    private void productTranslate(Integer id, StoreProduct storeProduct) throws IOException {
		String name = storeProduct.getStoreName(); // 待翻译内容
		String content = storeProduct.getStoreInfo(); // 待翻译内容
		
		// 更新的商品
		if(null != id) {
			// 查询是否存在源数据记录
			StoreProductTranslate storeProductTranslate = storeProductTranslateService.getOne(Wrappers.<StoreProductTranslate>lambdaQuery()
					.eq(StoreProductTranslate :: getProductId, storeProduct.getId())
					.last("LIMIT 1")
					);
			// 无数据直接翻译
			if(null == storeProductTranslate) {
				String nameT = bdTranslate(name);
				storeProduct.setStoreName(StringUtils.isNotBlank(nameT) ? nameT : name);
				
				String contentT = bdTranslate(content);
				storeProduct.setStoreInfo(StringUtils.isNotBlank(contentT) ? contentT : content);
				
				// 保存原始数据
				if(StringUtils.isNotBlank(nameT) || StringUtils.isNotBlank(contentT)) {
					storeProductTranslate = new StoreProductTranslate();
					storeProductTranslate.setProductId(id);
					storeProductTranslate.setName(name);
					storeProductTranslate.setDescription(content);
                    storeProductTranslate.setName(name);
                    storeProductTranslate.setDescription(content);

					storeProductTranslateService.save(storeProductTranslate);
				}
				
				return;
			}
			boolean update = false;
			// 翻译名字
			if(null != name && !name.equals(storeProductTranslate.getName())) {
				String nameT = bdTranslate(name);
				storeProduct.setStoreName(StringUtils.isNotBlank(nameT) ? nameT : name);
				storeProductTranslate.setName(name);
				update = true;
			}
			// 翻译内容
			if(null != content && !content.equals(storeProductTranslate.getDescription())) {
				String contentT = bdTranslate(content);
				storeProduct.setStoreInfo(StringUtils.isNotBlank(contentT) ? contentT : content);
				storeProductTranslate.setDescription(content);
				update = true;
			}
			if(update) {
				storeProductTranslateService.updateById(storeProductTranslate);
			}
		// 新数据直接翻译(拿不到商品id, 先不做处理)
		} else {
//			StoreProductTranslate storeProductTranslate = new StoreProductTranslate();
//			storeProductTranslate.setProductId(id);
//			// 翻译名字
//			String nameT = bdTranslate(name);
//			storeProduct.setStoreName(StringUtils.isNotBlank(nameT) ? nameT : name);
//			storeProductTranslate.setName(name);
//			// 翻译内容
//			String contentT = bdTranslate(content);
//			storeProduct.setStoreInfo(StringUtils.isNotBlank(contentT) ? contentT : content);
//			storeProductTranslate.setDescription(content);
//			storeProductTranslateService.updateById(storeProductTranslate);
		}
		
    }

    /**
     * 文本翻译  和分类名一样的内容不翻译
     * @author daigb
     * @throws IOException
     * @date:  2023-02-22 10:14
     */
    private void productTranslateNew(Integer id, StoreProduct storeProduct) throws IOException {
        String name = storeProduct.getStoreName(); // 待翻译内容
        String content = storeProduct.getStoreInfo(); // 待翻译内容
        String brandName = storeProduct.getBrandName();
        // 更新的商品
        if(null != id) {
            // 查询是否存在源数据记录
            StoreProductTranslate storeProductTranslate = storeProductTranslateService.getOne(Wrappers.<StoreProductTranslate>lambdaQuery()
                    .eq(StoreProductTranslate :: getProductId, storeProduct.getId())
                    .last("LIMIT 1")
            );
            // 无数据直接翻译
            if(null == storeProductTranslate) {
                String nameT = bdTranslate(name);
                storeProduct.setStoreName(StringUtils.isNotBlank(nameT) ? nameT : name);

                String contentT = bdTranslate(content);
                storeProduct.setStoreInfo(StringUtils.isNotBlank(contentT) ? contentT : content);

                // 保存原始数据
                if(StringUtils.isNotBlank(nameT) || StringUtils.isNotBlank(contentT)) {
                    storeProductTranslate = new StoreProductTranslate();
                    storeProductTranslate.setProductId(id);
                    storeProductTranslate.setName(name);
                    storeProductTranslate.setDescription(content);
                    storeProductTranslateService.save(storeProductTranslate);
                }

                return;
            }
            boolean update = false;
            // 翻译名字
            if(null != name && !name.equals(storeProductTranslate.getName())) {
                String nameT = bdTranslate(name);
                storeProduct.setStoreName(StringUtils.isNotBlank(nameT) ? nameT : name);
                storeProductTranslate.setName(name);
                update = true;
            }
            // 翻译内容
            if(null != content && !content.equals(storeProductTranslate.getDescription())) {
                String contentT = bdTranslate(content);
                storeProduct.setStoreInfo(StringUtils.isNotBlank(contentT) ? contentT : content);
                storeProductTranslate.setDescription(content);
                update = true;
            }
            if(update) {
                storeProductTranslateService.updateById(storeProductTranslate);
            }
            // 新数据直接翻译(拿不到商品id, 先不做处理)
        } else {
//			StoreProductTranslate storeProductTranslate = new StoreProductTranslate();
//			storeProductTranslate.setProductId(id);
//			// 翻译名字
//			String nameT = bdTranslate(name);
//			storeProduct.setStoreName(StringUtils.isNotBlank(nameT) ? nameT : name);
//			storeProductTranslate.setName(name);
//			// 翻译内容
//			String contentT = bdTranslate(content);
//			storeProduct.setStoreInfo(StringUtils.isNotBlank(contentT) ? contentT : content);
//			storeProductTranslate.setDescription(content);
//			storeProductTranslateService.updateById(storeProductTranslate);
        }

    }

    /**
     * 百度翻译
     * @author daigb
     * @date:  2023-01-30 10:30
     */
    private String bdTranslate(String q) throws IOException {
    	if(StringUtils.isBlank(q)) {
    		return null;
    	}
    	
    	String sign = MD5Util.encrypt(APPID + q + SALT + SECRET);
		String q2 = UriUtils.encode(q, "UTF-8");
		String url = BDURL + "?q=" + q2 + "&from=en&to=zh&appid=" + APPID + "&salt=" + SALT + "&sign=" + sign;
		
		String s = new OpenHttp().get(url, new HashMap<>());
		if(null != s) {
			JSONArray ja = JSONObject.parseObject(s).getJSONArray("trans_result");
			if(null != ja && 0 < ja.size()) {
				String s2 = ja.getJSONObject(0).getString("dst");
		    	return s2;
			}
		}
		
    	return null;
    }
    
    /**
     * 商品保存
     * @Description:  
     * @author daigb 
     * @param @param storeProductCrmebRequest
     * @param @param storeProduct
     * @param @param stock
     * @return void
     * @throws
     */
    @Transactional
    @Override
    public void saveOtProduct(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct, Integer stock) {
        if(storeProduct != null && !Objects.equals(storeProduct.getCommodityType(),1)){
            log.info("商品:{} 不是API接口下放",storeProductCrmebRequest.getBarCode());
            return;
        }
        if(ObjectUtils.isEmpty(storeProductCrmebRequest.getPrice()) || storeProductCrmebRequest.getPrice().compareTo(BigDecimal.ZERO) < 1){
            log.info("商品:{} 售价异常,不保存商品",storeProductCrmebRequest.getBarCode());
            return;
        }
        /****** 主表数据保存 *******/
        StoreProduct storeProductUpdate = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProductUpdate);
        storeProductUpdate.setStock(stock);
        storeProductUpdate.setUpdateFlag(true);
        // 替换季节
        replaceSeason(storeProductUpdate);
        
        boolean isUpdate = null != storeProduct;
        // 指定手动维护商品不更新指定字段
        if(isUpdate && storeProduct.getManualFlag()) {
    		storeProductUpdate.setStoreName(storeProduct.getStoreName());
    		storeProductUpdate.setKeyword(storeProduct.getKeyword());
    		storeProductUpdate.setColorCode(storeProduct.getColorCode());
    		storeProductUpdate.setSeasonCode(storeProduct.getSeasonCode());
        }
        //add by cdm 2023/08/07新增一个专门用户同步的syncKeyword
        storeProductUpdate.setSyncKeyword(storeProductCrmebRequest.getKeyword());
        if(!isUpdate){
            storeProductUpdate.setKeyword(storeProductCrmebRequest.getKeyword());
        }
        Integer productId = 0;
        String barCode = storeProductCrmebRequest.getBarCode();
        // 查询标准商品
    	String keyword = null == storeProductUpdate.getKeyword() ? "" : storeProductUpdate.getKeyword();
    	if(ProductTypeEnum.IM.getCode() != storeProductCrmebRequest.getIsEurope()) {
    		keyword = keyword.replaceAll(" ", "").replaceAll("\\\\", "").replaceAll("-", "").replaceAll("_", "").toUpperCase();
    	}
    	StoreProductNorm normProduct = StringUtils.isBlank(keyword) ? null : storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
    			.eq(StoreProductNorm :: getKeyword, keyword)
    			.last("LIMIT 1")
    			);

    	// 新增标准商品
    	boolean imStatus = false;
    	boolean jkyStatus = false;
    	if(ProductTypeEnum.IM.getCode() == storeProductCrmebRequest.getIsEurope() && !brandIds.contains(storeProductCrmebRequest.getBrandId())) {
    		imStatus = true;
    	}
//    	if(ProductTypeEnum.JKY.getCode() == storeProductCrmebRequest.getIsEurope() && brandIds.contains(storeProductCrmebRequest.getBrandId())) {
    	if(ProductTypeEnum.JKY.getCode() == storeProductCrmebRequest.getIsEurope()) {
    		jkyStatus = true;
    	}
    	if((imStatus || jkyStatus) && StringUtils.isNotBlank(keyword)) {
    		if(null == normProduct) {
    			normProduct = new StoreProductNorm();
    			BeanUtils.copyProperties(storeProductUpdate, normProduct);
    			storeProductNormService.save(normProduct);
    		} else {
    			int normId = normProduct.getId();
                // 判断原标品属于哪个供应商 im不覆盖诚品 诚品覆盖im
                if(null != normProduct.getSuppliersId()){
                    if (Integer.parseInt(normProduct.getSuppliersId()) != 174 || jkyStatus) {
                        BeanUtils.copyProperties(storeProductUpdate, normProduct);
                    }
                }
    			normProduct.setId(normId);
        		storeProductNormService.updateById(normProduct);
    		}
    	}
    	// 使用标准商品配置
//    	if(null != normProduct && !imStatus && !jkyStatus) {
    	if(null != normProduct && !imStatus && !jkyStatus && ProductTypeEnum.COLTORTI.getCode() != storeProductCrmebRequest.getIsEurope()) {
    		// 不可绑定状态判断
    		//if(!isUpdate || 1 != storeProduct.getTmall()) {
    			convertProduct(normProduct, storeProductUpdate);
    		//}
    	}
    	// 使用当前汇率
    	if(null == storeProductUpdate.getExchangeRate()) {
    		MoneyExchange moneyExchange = moneyExchangeService.getExchangeByName(Constants.EXCHANGE_EUR_NAME);
    		String eurRate = null == moneyExchange ? PriceUtil.DEFAULT_EXCHANGE_RATE_EUR : moneyExchange.getBankConversionPri();
    		storeProductUpdate.setExchangeRate(new BigDecimal(eurRate));
    	}
    	if(null == storeProductUpdate.getIsEurope() || storeProductUpdate.getIsEurope() == 1 || storeProductUpdate.getIsEurope() == 999) {
    		log.error("===================== 商品标识异常: {}, 货品: {} ===================", isUpdate, JSON.toJSONString(storeProductUpdate));
    		return;
    	}
    	// 翻译
    	if(null == storeProductUpdate.getNormId() && -1 != translateIds.indexOf(storeProductUpdate.getIsEurope())) {
    		try {
				Integer translateId = isUpdate ? storeProduct.getId() : null;
				productTranslate(translateId, storeProductUpdate);
			} catch (IOException e) {
	    		log.error("===================== 百度翻译异常 ===================");
			}
    	}
        if (isUpdate) {
            this.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getId, storeProduct.getId())
                    .set(StoreProduct::getPrice, storeProductUpdate.getPrice())
                    .set(null != storeProductUpdate.getPromotePrice(), StoreProduct::getPromotePrice, storeProductUpdate.getPromotePrice())
                    .set(null != storeProductUpdate.getVipPrice(), StoreProduct::getVipPrice, storeProductUpdate.getVipPrice())
                    .set(null != storeProductUpdate.getStoreName(), StoreProduct::getStoreName, storeProductUpdate.getStoreName())
                    .set(null != storeProductUpdate.getColorCode(), StoreProduct::getColorCode, storeProductUpdate.getColorCode())
                    .set(null != storeProductUpdate.getSeasonCode(), StoreProduct::getSeasonCode, storeProductUpdate.getSeasonCode())
                    //.set(null != storeProductUpdate.getKeyword(), StoreProduct::getKeyword, storeProductUpdate.getKeyword())
                    .set(null != storeProductUpdate.getSyncKeyword(), StoreProduct::getSyncKeyword, storeProductUpdate.getSyncKeyword())
                    .set(null != storeProductUpdate.getOtPrice(), StoreProduct::getOtPrice, storeProductUpdate.getOtPrice())
                    .set(null != storeProductUpdate.getPostage(), StoreProduct::getPostage, storeProductUpdate.getPostage())
                    .set(null != storeProductUpdate.getBrandId(), StoreProduct::getBrandId, storeProductUpdate.getBrandId())
                    .set(null != storeProductUpdate.getBrandName(), StoreProduct::getBrandName, storeProductUpdate.getBrandName())
                    .set(null != storeProductUpdate.getSuppliersId(), StoreProduct::getSuppliersId, storeProductUpdate.getSuppliersId())
                    .set(null != storeProductUpdate.getSuppliersName(), StoreProduct::getSuppliersName, storeProductUpdate.getSuppliersName())
                    .set(null != storeProductUpdate.getCateId(), StoreProduct::getCateId, storeProductUpdate.getCateId())
                    .set(null != storeProductUpdate.getGiveIntegral(), StoreProduct::getGiveIntegral, storeProductUpdate.getGiveIntegral())
                    .set(null != storeProductUpdate.getCost(), StoreProduct::getCost, storeProductUpdate.getCost())
                    .set(null != storeProductUpdate.getSourceCost(), StoreProduct::getSourceCost, storeProductUpdate.getSourceCost())
                    .set(null != storeProductUpdate.getSpecType(), StoreProduct::getSpecType, storeProductUpdate.getSpecType())
                    .set(null != storeProductUpdate.getCreateTime(), StoreProduct::getCreateTime, storeProductUpdate.getCreateTime())
                    .set(null != storeProductUpdate.getLastPushTime(), StoreProduct::getLastPushTime, storeProductUpdate.getLastPushTime())
//                    .set(null != storeProductUpdate.getIsEurope(), StoreProduct::getIsEurope, storeProductUpdate.getIsEurope())
                    .set(null != storeProductUpdate.getTempId(), StoreProduct::getTempId, storeProductUpdate.getTempId())
//                    .set(null == storeProduct.getImage() || ProductTypeEnum.JKY.getCode() == storeProductCrmebRequest.getIsEurope() || ProductTypeEnum.IM.getCode() == storeProductCrmebRequest.getIsEurope(), StoreProduct::getImage, storeProductUpdate.getImage())
                    .set(StoreProduct::getNormId, storeProductUpdate.getNormId())
                    .set(StoreProduct::getUpdateFlag, storeProductUpdate.getUpdateFlag())
                    .set(StoreProduct::getExchangeRate, storeProductUpdate.getExchangeRate())
                    .set(!storeProduct.getTmall(),  StoreProduct::getIsShow, true)
                    .set(StoreProduct::getIsDel, false)
                    .set(StoreProduct::getStock, stock)
//                    .set(StoreProduct::getTmall, storeProductUpdate.getTmall())
                    );
            productId = storeProduct.getId();
            barCode = storeProduct.getBarCode();
        } else {
        	storeProductUpdate.setCreateTime(new Date());
//        	storeProductUpdate.setCreateTime(new Date());
            storeProductUpdate.setCommodityType(1);
            this.save(storeProductUpdate);
            productId = storeProductUpdate.getId();
            //自动下架
            List<ChannelMerchant> merchantList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery().eq(ChannelMerchant::getIsDel, 0).eq(ChannelMerchant::getAutomaticShelves, 0).select(ChannelMerchant::getId));
            merchantList.forEach(mer->{
            	MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(mer.getId()));
                StoreProductMer storeMerProduct = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                        .eq(StoreProductMer :: getProductId, storeProductUpdate.getId())
                        .last("LIMIT 1"));
                if(null == storeMerProduct) {
                    storeMerProduct = new StoreProductMer();
                    storeMerProduct.setProductId(storeProductUpdate.getId());
                    storeMerProduct.setIsNotShow(1);
                    storeMerProduct.setIsSystemOut(1);
                    storeMerProduct.setCreateTime(new Date());
                    storeMerProduct.setUpdateTime(new Date());
                    storeProductMerService.save(storeMerProduct);
                }
            });
        }
        /****** attr表保存 ********/
        if (isUpdate) {
            storeProductAttrService.removeByProductId(productId);
        }
        List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
        for (StoreProductAttr attr : attrs) {
            attr.setProductId(productId);
            attr.setBarCode(barCode);
            attr.setAttrValues(StringUtils.strip(attr.getAttrValues().replace("\"", ""), "[]"));
        }
        storeProductAttrService.saveBatch(attrs);
        /****** value表保存 *********/
//        Map<String, StoreProductAttrValue> dbStoreProductAttrValueMap = new HashMap<>();
//        if (isUpdate) {
////            List<StoreProductAttrValue> dbStoreProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, productId));
////            dbStoreProductAttrValueMap = dbStoreProductAttrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, s -> s, (value1, value2) -> {
////                return value1;
////            }));
//            // 删除所有value
//            storeProductAttrValueService.removeByProductId(productId);
//        }
        List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
        List<StoreProductAttrValue> values = new ArrayList<>();
        storeProductAttrValuesRequest = new ArrayList<>(storeProductAttrValuesRequest.stream()
                .collect(Collectors.toMap(StoreProductAttrValueRequest::getSourceSkuId, a -> a, (o1, o2) -> o1)).values());
        for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
            attrValuesRequest.setProductId(productId);
            attrValuesRequest.setBarCode(barCode);
            attrValuesRequest.setSourceSkuId(storeProductCrmebRequest.getIsEurope() + "-" + attrValuesRequest.getSourceSkuId());
            StoreProductAttrValue spav = new StoreProductAttrValue();
            BeanUtils.copyProperties(attrValuesRequest, spav);
            List<String> skuList = new ArrayList<>();
            for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                skuList.add(vo.getValue());
                spav.setSuk(String.join(",", skuList));
            }
            spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
            spav.setSelfSourceSkuId(attrValuesRequest.getSelfSourceSkuId());
            values.add(spav);
        }
        //storeProductAttrValueService.saveBatch(values);
        if (isUpdate) {
            // 是否吉客云
            boolean b = Objects.nonNull(values.get(0).getSelfSourceSkuId());
            if (b) {
                storeProductAttrValueService.updateBatchByQueryWrapper(values, value -> Wrappers.<StoreProductAttrValue>lambdaQuery()
                        .eq(StoreProductAttrValue::getSelfSourceSkuId, value.getSelfSourceSkuId())
                        .eq(StoreProductAttrValue::getProductId, value.getProductId()));
            }
            storeProductAttrValueService.updateBatchByQueryWrapper(values, value -> Wrappers.<StoreProductAttrValue>lambdaQuery()
                    .eq(StoreProductAttrValue::getProductId, value.getProductId())
                    .eq(StoreProductAttrValue::getSourceSkuId, value.getSourceSkuId()));
            List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, productId));
            if (CollectionUtils.isNotEmpty(storeProductAttrValues)) {
                if (b) {
                    List<String> selfSourceSkuIds = storeProductAttrValues.stream().map(StoreProductAttrValue::getSelfSourceSkuId).collect(Collectors.toList());
                    List<Integer> productIds = storeProductAttrValues.stream().map(StoreProductAttrValue::getProductId).collect(Collectors.toList());
                    values = values.stream().filter(e -> !(productIds.contains(e.getProductId()) && selfSourceSkuIds.contains(e.getSelfSourceSkuId()))).collect(Collectors.toList());
                } else {
                    List<Integer> productIds = storeProductAttrValues.stream().map(StoreProductAttrValue::getProductId).collect(Collectors.toList());
                    List<String> sourceSkuIds = storeProductAttrValues.stream().map(StoreProductAttrValue::getSourceSkuId).collect(Collectors.toList());
                    values = values.stream().filter(e -> !(productIds.contains(e.getProductId()) && sourceSkuIds.contains(e.getSourceSkuId()))).collect(Collectors.toList());
                }
            }
            if (CollectionUtils.isNotEmpty(values)) {
                storeProductAttrValueService.saveBatch(values);
            }
        } else {
            storeProductAttrValueService.saveBatch(values);
        }
        /****** result表保存 ******/
        if (isUpdate) {
            storeProductAttrResultService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, productId));
        }
        StoreProductAttrResult attrResult = new StoreProductAttrResult(productId, systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductAttrValuesRequest)), Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, barCode);
        storeProductAttrResultService.save(attrResult);

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, productId)
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProductUpdate);
        storeProductDescription.setProductId(productId);
        if(ObjectUtil.isNull(dbDescription) || StringUtils.isBlank(dbDescription.getImage()) || ProductTypeEnum.JKY.getCode() == storeProductCrmebRequest.getIsEurope() || ProductTypeEnum.IM.getCode() == storeProductCrmebRequest.getIsEurope()) {
        	storeProductDescription.setImage(storeProductUpdate.getImage());
        }
        if(ObjectUtil.isNull(dbDescription) || StringUtils.isBlank(dbDescription.getSliderImage()) || ProductTypeEnum.JKY.getCode() == storeProductCrmebRequest.getIsEurope() || ProductTypeEnum.IM.getCode() == storeProductCrmebRequest.getIsEurope()) {
        	storeProductDescription.setSliderImage(storeProductUpdate.getSliderImage());
        }
        if(ObjectUtil.isNull(dbDescription)) {
            storeProductDescriptionService.save(storeProductDescription);
        } else {
        	storeProductDescription.setId(dbDescription.getId());
        	storeProductDescriptionService.updateById(storeProductDescription);
        }
    }

    /**
     * 
     * @Description:  
     * @author daigb 
     * @param @param sourceProduct 标准商品数据
     * @param @param targetProduct 要替换的商品
     * @return void
     * @throws
     */
    private void convertProduct(StoreProductNorm sourceProduct, StoreProduct targetProduct) {
        if(StringUtil.isNotEmpty(sourceProduct.getStoreName())) {
            targetProduct.setStoreName(sourceProduct.getStoreName());
        }
        if(StringUtil.isNotEmpty(sourceProduct.getStoreInfo())) {
            targetProduct.setStoreInfo(sourceProduct.getStoreInfo());
        }
        if(StringUtil.isNotEmpty(sourceProduct.getComposition())) {
            targetProduct.setComposition(sourceProduct.getComposition());
        }
        if(StringUtil.isNotEmpty(sourceProduct.getDimension())) {
            targetProduct.setDimension(sourceProduct.getDimension());
        }
        if(StringUtil.isNotEmpty(sourceProduct.getColorCode())) {
            targetProduct.setColorCode(sourceProduct.getColorCode());
        }
        if(StringUtil.isNotEmpty(sourceProduct.getSeasonCode())) {
            targetProduct.setSeasonCode(sourceProduct.getSeasonCode());
        }
//        if(StringUtil.isNotEmpty(sourceProduct.getImage())) {
//            targetProduct.setImage(sourceProduct.getImage());
//        }
//        if(StringUtil.isNotEmpty(sourceProduct.getSliderImage())) {
//            targetProduct.setSliderImage(sourceProduct.getSliderImage());
//        }
        if(null != sourceProduct.getBrandId()) {
            targetProduct.setBrandId(sourceProduct.getBrandId());
        }
        if(null != sourceProduct.getBrandName()) {
            targetProduct.setBrandName(sourceProduct.getBrandName());
        }
        if(null != sourceProduct.getCateId()) {
            targetProduct.setCateId(sourceProduct.getCateId());
            targetProduct.setWeight(sourceProduct.getWeight());
        }
        targetProduct.setNormId(sourceProduct.getId());
    }
    
    /**
     * 非标准季节替换
     * @author daigb
     * @date:  2022-09-27 16:17
     */
    private void replaceSeason(StoreProduct storeProduct) {
    	String seasonCode = storeProduct.getSeasonCode();
    	if(StringUtils.isBlank(seasonCode)) {
    		return;
    	}
        if ("2019Spring / Summer".equals(seasonCode) || "19S".equals(seasonCode)) {
            storeProduct.setSeasonCode("19SS");
        }
        if ("Fall Winter 2019/20".equals(seasonCode)) {
            storeProduct.setSeasonCode("19FW");
        }
    	if("20AW".equals(seasonCode) || "Fall Winter 2020/21".equals(seasonCode) || "2020Fall / Winter".equals(seasonCode) || "20W".equals(seasonCode) || "2020FW".equals(seasonCode) || "2020W-FW".equals(seasonCode)) {
    		storeProduct.setSeasonCode("20FW");
    	}
        if ("Spring Summer 2020".equals(seasonCode) || "2020Spring / Summer".equals(seasonCode) || "20S".equals(seasonCode) || "2020S-SS".equals(seasonCode) || "2020Spring - Summer".equals(seasonCode) || "2020SS".equals(seasonCode)) {
            storeProduct.setSeasonCode("20SS");
        }
    	if("SS21".equals(seasonCode) || "Spring Summer 2021".equals(seasonCode) || "2021Spring / Summer".equals(seasonCode) || "21S".equals(seasonCode) || "2021Spring - Summer".equals(seasonCode)) {
    		storeProduct.setSeasonCode("21SS");
    	}
    	if("FW21".equals(seasonCode) || "21aw".equals(seasonCode) || "2021秋冬".equals(seasonCode) || "AW21".equals(seasonCode) || "Fall Winter 2021".equals(seasonCode) || "Fall Winter 2021/22".equals(seasonCode) || "2021Fall / Winter".equals(seasonCode) || "21W".equals(seasonCode) || "2021Fall - winter".equals(seasonCode) || "2021FW".equals(seasonCode)) {
    		storeProduct.setSeasonCode("21FW");
    	}
    	if("SS22".equals(seasonCode) || "Spring Summer 2022".equals(seasonCode) || "2022Spring / Summer".equals(seasonCode) || "2022Spring - Summer".equals(seasonCode) || "22S".equals(seasonCode)) {
    		storeProduct.setSeasonCode("22SS");
    	}
        if ("Fall Winter 2022/2023".equals(seasonCode) || "2022Fall / Winter".equals(seasonCode) || "22W".equals(seasonCode) || "2022Fall - winter".equals(seasonCode) || "Fall Winter 2022/23".equals(seasonCode)) {
            storeProduct.setSeasonCode("22FW");
        }
        if ("Spring Summer 2023".equals(seasonCode) || "23S".equals(seasonCode) || "2023Spring - Summer".equals(seasonCode) || "SS23".equals(seasonCode) || "2023Spring / Summer".equals(seasonCode)) {
            storeProduct.setSeasonCode("23SS");
        }
        if ("2023Fall - winter".equals(seasonCode) || "Fall Winter 2023/2024".equals(seasonCode) || "2023Fall / Winter".equals(seasonCode) || "23W".equals(seasonCode)) {
            storeProduct.setSeasonCode("23FW");
        }
        if ("CarryOver".equals(seasonCode) || "Carryover".equals(seasonCode) || seasonCode.contains("Carry over")) {
            storeProduct.setSeasonCode("CO");
        }
    }

	@Override
	public void downloadSku(Integer isEurope) {
        storeProductMapper.downloadSku(isEurope);
	}

	/**
	 * TODO 图搜功能目前弃用 dai
	 */
	@Override
	public void delSeachImage(ProductTypeEnum type) {
        // 删除图搜商品
//        List<StoreProduct> storeProductBarcodes = this.list(Wrappers.<StoreProduct>lambdaQuery()
//                .eq(StoreProduct::getIsEurope, type.getCode())
//                .eq(StoreProduct::getUpdateFlag, false)
//                .eq(StoreProduct::getIsTusou, true)
//                .eq(StoreProduct::getIsShow, true)
//                .select(StoreProduct :: getBarCode)
//                );
//        log.info("--------------- {}待删除图搜总数: {} ---------------", type.getMsg(), storeProductBarcodes.size());
//        for(StoreProduct storeProduct : storeProductBarcodes) {
//            try {
//                ImageSearchUtils.deleteImage(storeProduct.getBarCode(), null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
	}

	@Override
	public void delSeachImageByBarcode(String barcode) {
        try {
            ImageSearchUtils.deleteImage(barcode, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

    @Override
    public void testFanyi() {

            List<StoreProductTranslate> list = storeProductTranslateService.list();

           for(StoreProductTranslate storeProductTranslate : list) {

            try {
                String name = storeProductTranslate.getName(); // 待翻译内容
                String content = storeProductTranslate.getDescription(); // 待翻译内容
                log.info("--------------- name: ---------------" + name);
                log.info("--------------- content: ---------------" + content);
                String rName =  name.replaceAll("Max mara","{1}" );
                String rcontent =  content.replaceAll("Max Mara","{2}");

                log.info("--------------- rName: ---------------" + rName);
                log.info("--------------- rcontent: ---------------" + rcontent);

                String nameT = bdTranslate(rName);
                String contentT = bdTranslate(rcontent);
                log.info("--------------- nameT: ---------------" + nameT);
                log.info("--------------- nameT: ---------------" + contentT);

                String rNameNew =  nameT.replace("{1}","Max mar" );
                String rcontentNew =  contentT.replace("{2}","Max Mar");

                log.info("--------------- rNameNew: ---------------" + rNameNew);
                log.info("--------------- rcontentNew: ---------------" + rcontentNew);

            } catch (Exception e) {
                e.printStackTrace();
            }
         }


    }
    
}
